<template>
<div id="box">
        <!--面包屑区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!--卡片视图-->
<el-card>
    <!--添加角色按钮-->
    <el-row>
        <el-col><el-button type="primary" @click="addRule()">添加角色</el-button></el-col>
    </el-row>
<!--角色区域列表-->
<el-table :data="ruleList" border stripe>
    <el-table-column type="expand">
        <template v-slot="scope">
         <el-row :class="['bottom', 'center', index1  ===  0 ? 'top' : '']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
            <!--一级权限-->
            <el-col :span="5">
              <el-tag  closable @close="removeID(scope.row,item.id)">{{ item1.authName }}</el-tag>  
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!--二级和三级权限-->
            <el-col :span="19">
                <!--二级权限-->
             <el-row :class="['center',index2===0 ? '' : 'top']" v-for="(item2,index2) in item1.children" :key="item2.id">
                <el-col :span="6">
                    <el-tag type="success"  closable @close="removeID(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                </el-col>
                <!--三级权限-->
                <el-col :span="18">
                  <el-tag  closable type="warning" v-for="(item3,index3) in item2.children" :key="item3.id" @close="removeID(scope.row,item3.id)">{{item3.authName}}</el-tag>
                </el-col>
             </el-row>
            </el-col>
        </el-row>
        </template>
    </el-table-column>
<el-table-column type="index" label="#"></el-table-column>
<el-table-column label="角色名称" prop="roleName"></el-table-column>
<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
<el-table-column label="操作" width="300px">
    <template v-slot="scope">
        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRule(scope.row.id)">编辑</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRule(scope.row.id)">删除</el-button>
        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightByid(scope.row)">分配权限</el-button>
    </template>
</el-table-column>
</el-table>
</el-card>
<!--添加对话框-->
<el-dialog
  title="添加角色"
  :visible.sync="addVisible"
  width="50%"
  @close="closeadd"
  >
  <el-form :model="addForm" :rules="addreg" ref="addref" label-width="100px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="addForm.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="addForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addVisible = false">取 消</el-button>
    <el-button type="primary" @click="addqd">确 定</el-button>
  </span>
</el-dialog>
<!--修改对话框-->
<el-dialog
  title="编辑角色"
  :visible.sync="editVisible"
  width="50%"
   @close="closeedit"
  >
  <el-form :model="editForm" :rules="addreg" ref="editref" label-width="100px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="editForm.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editVisible = false">取 消</el-button>
    <el-button type="primary" @click="editqd">确 定</el-button>
  </span>
</el-dialog>
<!--分配权限对话框-->
<el-dialog
  title="分配权限"
  :visible.sync="fpVisible"
  width="50%" @close="closefpqx">
  <el-tree :data="rightsList" :props="defaultProps"   show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="deKeys" ref="treeref"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="fpVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights()">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
import { async } from 'rxjs'

export default {
    data() {
        return {
            //所有角色列表数据
            ruleList: [],
             //所有权限列表数据
             rightsList: [],
             //默认勾选的权限
             deKeys: [],
             defaultProps: {
                label: 'authName',
                children: 'children'
             },
             //角色id
             roleID: 0,
            //对话框的显示
            addVisible: false,
            editVisible: false,
            fpVisible: false,
            //添加角色数据
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            editForm: {},
            //验证规则
            addreg: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ]
            }
        }
    },
    created: function () {
        this.getRuleList()
    },
    methods: {
        //获取所有角色列表
        async getRuleList() {
            let { data } = await this.$http.get("roles")
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("角色列表获取失败")
            this.ruleList = data.data
        },
        //点击添加角色
        addRule() {
            this.addVisible = true
        },
        //关闭对话框
        closeadd() {
            this.$refs.addref.resetFields()
        },
        //点击确定，新增角色
        addqd() {
            this.$refs.addref.validate(async (bool) => {
                if (!bool) return
                let { data } = await this.$http.post("roles", this.addForm)
                // console.log(data)
                if (data.meta.status !== 201) return this.$message.error("新增角色失败")
                this.$message.success("新增角色成功")
                this.addVisible = false
                this.getRuleList()
            })
        },
        //点击编辑
        async editRule(id) {
            let { data } = await this.$http.get("roles/" + id)
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("编辑角色渲染失败")
            this.editForm = data.data
            this.editVisible = true
        },
        closeedit() {
            this.$refs.editref.resetFields()
        },
        //点击确定，进行编辑
        editqd() {
            this.$refs.editref.validate(async (bool) => {
                if (!bool) return
                let { data } = await this.$http.put("roles/" + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
                if (data.meta.status !== 200) this.$message.error("编辑角色失败")
                this.$message.success("编辑用户成功")
                this.editVisible = false
                this.getRuleList()
            })
        },
        //点击删除，进行删除
        async deleteRule(id) {
            let h = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (h !== 'confirm') return this.$message("已取消删除")
            let { data } = await this.$http.delete("roles/" + id)
            if (data.meta.status !== 200) return this.$message.error("删除失败")
            this.$message.success("删除成功")
            this.getRuleList()
        },
        //删除指定权限
       async removeID(id1,id2){
           let h=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(h!=='confirm'){
            return this.$message("已取消删除")
        }
        let {data}=await this.$http.delete(`roles/${id1.id}/rights/${id2}`)
       if(data.meta.status!==200) return this.$message.error("删除权限失败")
       this.$message.success("删除权限成功")
         id1.children=data.data
        },
        //点击分配权限
       async showSetRightByid(role){
        this.roleID=role.id
            //获取所有权限数据
                let {data}=await this.$http.get("rights/tree")
                // console.log(data)
                if(data.meta.status!==200) return this.$message.error("权限数据获取失败")
                this.rightsList=data.data
                //递归
               this.getLeafKeys(role,this.deKeys)
            this.fpVisible=true
        },
        //通过递归拿到三级权限的id
        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach((item)=>{
                this.getLeafKeys(item,arr)
            })
        },
        //关闭对话框
        closefpqx(){
            this.deKeys=[]
        },
        //点击确定，分配权限
       async allotRights(){
        let keys=[...this.$refs.treeref.getCheckedKeys(),...this.$refs.treeref.getHalfCheckedKeys()]
    // console.log(keys)
    let idstr=keys.join(",")
    let {data}=await this.$http.post(`roles/${this.roleID}/rights`,{rids:idstr})
 if(data.meta.status!==200) return this.$message.error("分配权限失败")
 this.$message.success("权限分配成功")
 this.getRuleList()
 this.fpVisible=false
 
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.top {
    border-top: 1px solid #eee;
}

.bottom {
    border-bottom: 1px solid #eee
}
.center{
    display: flex;
    align-items: center;
}
</style>